package org.lq.ht.view.viewSale;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSplitPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.lq.ht.entity.Goods;
import org.lq.ht.entity.Room;
import org.lq.ht.entity.Sales;
import org.lq.ht.service.GoodsService;
import org.lq.ht.service.SalesService;
import org.lq.ht.service.impl.GoodsServiceImpl;
import org.lq.ht.service.impl.SalesServiceImpl;
import org.lq.ht.util.AutoNo;
import org.lq.ht.util.CastUtil;
import org.lq.ht.view.goods.goodsMain;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
/**消费记账视图
 *
 * @package org.lq.ht.view.viewSale
 * @date 2020年8月21日下午11:28:22
 */
public class SaleAccount extends JFrame {
	private JPanel contentPane;
	private JTextField textField;
	private JTable table;
	private JTextField textField_1;

	private  Map<Goods, Integer> goodsMap = new HashMap<Goods, Integer>();;
	private List<Sales> list = new ArrayList<Sales>();

	private int roomId;
	private Long sales_num ;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SaleAccount frame = new SaleAccount();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SaleAccount() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 782, 653);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));

		JSplitPane splitPane = new JSplitPane();
		panel.add(splitPane, BorderLayout.NORTH);

		JPanel panel_1 = new JPanel();
		splitPane.setLeftComponent(panel_1);

		JLabel lblNewLabel = new JLabel("在住房客");
		panel_1.add(lblNewLabel);

		textField = new JTextField();
		panel_1.add(textField);
		textField.setColumns(10);

		JButton btnNewButton = new JButton("检索");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//房间检索
				SelectSales main = new SelectSales();
				main.setVisible(true);
				main.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						roomId = main.getRoomID();
						textField.setText(roomId+"");
						sales_num = AutoNo.getSalesNo();
					}
				});

			}
		});
		panel_1.add(btnNewButton);

		JLabel lblNewLabel_1 = new JLabel("商品");
		panel_1.add(lblNewLabel_1);

		textField_1 = new JTextField();
		panel_1.add(textField_1);
		textField_1.setColumns(10);

		JButton btnNewButton_3 = new JButton("检索");
		btnNewButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//商品检索
				if(roomId==0) {
					JOptionPane.showMessageDialog(SaleAccount.this, "请先检索房间！");
				}else {

					goodsMain main = new goodsMain();
					main.setBounds(SaleAccount.this.getX(), SaleAccount.this.getY(), main.getWidth(), main.getHeight());
					main.setVisible(true);
					main.addWindowListener(new WindowAdapter() {

						@Override
						public void windowClosed(WindowEvent e) {
							int id = 0;
							try {
								id = main.getGoodsId();
							} catch (NullPointerException e2) {
								System.out.println("空指针");
							}
							if(id!=0) {
								GoodsService gs = new GoodsServiceImpl();
								Goods g = gs.getById(id);
								textField_1.setText(g.getName());

								if(goodsMap.isEmpty()) {
									goodsMap.put(g, 1);
									initTable(goodsMap);
								}else {
									Set<Goods> keySet = goodsMap.keySet();
									for (Goods good : keySet) {
										if(good.equals(g)) {
											int num = goodsMap.get(good);
											goodsMap.put(good, num+1);
										}else {
											goodsMap.put(g, 1);
										}
									}
									initTable(goodsMap);

								}
							}
						}
					});
				}

			}
		});
		panel_1.add(btnNewButton_3);

		JPanel panel_2 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_2.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		splitPane.setRightComponent(panel_2);

		JButton btnNewButton_2 = new JButton("保存");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//保存
				SalesService ss = new SalesServiceImpl();
				Sales sales = ss.findByRoomId(roomId);
				goodsMap.forEach((g,n)->{
					sales.setOrder_num(CastUtil.castInt(sales_num));
					sales.setGoods_name(g.getName());
					sales.setGoods_num(n);
					sales.setGoods_price(g.getPurchase_price());
					sales.setBill_date(new Timestamp(System.currentTimeMillis()));
					
					ss.saveSales(sales);
				});

				JOptionPane.showMessageDialog(SaleAccount.this, "保存成功！");
				initTable(goodsMap);
				//清空
				goodsMap.clear();
			}
		});
		panel_2.add(btnNewButton_2);

		JButton btnNewButton_1 = new JButton("重置");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//重置
				goodsMap=null;
				textField.setText("");
				textField_1.setText("");
			}
		});
		panel_2.add(btnNewButton_1);

		JPanel panel_3 = new JPanel();
		contentPane.add(panel_3, BorderLayout.CENTER);
		panel_3.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		panel_3.add(scrollPane, BorderLayout.CENTER);

		table = new JTable();
		table.setModel(new DefaultTableModel(
				new Object[][] {
					{null, null, null, null, null, null, null, null, null, null, null, null, null},
					{null, null, null, null, null, null, null, null, null, null, null, null, null},
				},
				new String[] {
						"\u5E8F\u53F7", "\u9500\u552E\u5355\u53F7", "\u623F\u95F4\u53F7", "\u5546\u54C1\u53F7", "\u5546\u54C1\u7B80\u79F0", "\u5546\u54C1\u540D\u79F0", "\u5546\u54C1\u6570\u91CF", "\u5546\u54C1\u5355\u4F4D", "\u5546\u54C1\u8FDB\u4EF7", "\u91D1\u989D", "\u5F00\u59CB\u65F6\u95F4", "\u7ED3\u7B97\u65F6\u95F4", "\u8BB0\u8D26\u65F6\u95F4"
				}
				));
		table.getColumnModel().getColumn(3).setMinWidth(0);
		table.getColumnModel().getColumn(3).setMaxWidth(0);
		scrollPane.setViewportView(table);

		JPopupMenu popupMenu = new JPopupMenu();
		addPopup(table, popupMenu);

		JMenuItem mntmNewMenuItem_1 = new JMenuItem("减少");
		mntmNewMenuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//商品数量-1
				int index = table.getSelectedRow();
				int goodsNumber = CastUtil.castInt(table.getValueAt(index, 3));
				GoodsService gs = new GoodsServiceImpl();
				Goods g = gs.getBynumber(goodsNumber);

				Set<Goods> keySet = goodsMap.keySet();
				for (Goods good : keySet) {
					if(good.equals(g)) {
						int num = goodsMap.get(good);
						if(num-1==0) {
							int n = JOptionPane.showConfirmDialog(SaleAccount.this, "确定删除！");
							if(n==0) {
								if(goodsMap.remove(good)!=0) {
									JOptionPane.showMessageDialog(SaleAccount.this, "删除成功！");
								}else {
									JOptionPane.showMessageDialog(SaleAccount.this, "删除失败！");
								}
							}
						}else {
							goodsMap.put(good, num-1);
						}
					}
				}
				initTable(goodsMap);
			}
		});

		JMenuItem mntmNewMenuItem_3 = new JMenuItem("增加");
		mntmNewMenuItem_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//商品数量+1
				int index = table.getSelectedRow();
				System.out.println(index);
				int goodsNumber = CastUtil.castInt(table.getValueAt(index, 3));
				System.out.println(goodsNumber);
				GoodsService gs = new GoodsServiceImpl();
				Goods g = gs.getBynumber(goodsNumber);

				Set<Goods> keySet = goodsMap.keySet();
				for (Goods good : keySet) {
					if(good.equals(g)) {
						int num = goodsMap.get(good);
						goodsMap.put(good, num+1);
					}
				}
				initTable(goodsMap);
			}
		});
		popupMenu.add(mntmNewMenuItem_3);
		popupMenu.add(mntmNewMenuItem_1);

		JMenuItem mntmNewMenuItem = new JMenuItem("删除");
		mntmNewMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//商品删除
				int index = table.getSelectedRow();
				int goodsNumber = CastUtil.castInt(table.getValueAt(index, 3));
				GoodsService gs = new GoodsServiceImpl();
				Goods g = gs.getBynumber(goodsNumber);

				Set<Goods> keySet = goodsMap.keySet();
				for (Goods good : keySet) {
					if(good.equals(g)) {
						int num = goodsMap.get(good);
						int n = JOptionPane.showConfirmDialog(SaleAccount.this, "确定删除！");
						if(n==0) {
							if(goodsMap.remove(good)!=0) {
								JOptionPane.showMessageDialog(SaleAccount.this, "删除成功！");
							}else {
								JOptionPane.showMessageDialog(SaleAccount.this, "删除失败！");
							}
						}
					}
				}
				initTable(goodsMap);
			}
		});

		JSeparator separator = new JSeparator();
		popupMenu.add(separator);

		JMenuItem mntmNewMenuItem_2 = new JMenuItem("数量控制");
		mntmNewMenuItem_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//数量控制
				int index = table.getSelectedRow();
				int goodsNumber = CastUtil.castInt(table.getValueAt(index, 3));
				GoodsService gs = new GoodsServiceImpl();
				Goods g = gs.getBynumber(goodsNumber);

				Set<Goods> keySet = goodsMap.keySet();
				for (Goods good : keySet) {
					if(good.equals(g)) {
						int num =Integer.parseInt(JOptionPane.showInputDialog(SaleAccount.this, "请输入数量！"));
						if(num==0) {
							int n = JOptionPane.showConfirmDialog(SaleAccount.this, "确定删除！");
							if(n==0) {
								if(goodsMap.remove(good)!=0) {
									JOptionPane.showMessageDialog(SaleAccount.this, "删除成功！");
								}else {
									JOptionPane.showMessageDialog(SaleAccount.this, "删除失败！");
								}
							}
						}else {
							goodsMap.put(good, num);
						}
					}
				}
				initTable(goodsMap);
			}
		});
		popupMenu.add(mntmNewMenuItem_2);
		popupMenu.add(mntmNewMenuItem);
	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}

	public void initTable(Map<Goods, Integer> map){

		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		SalesService ss = new SalesServiceImpl();
		int count = dtm.getRowCount();
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		map.forEach((g,n)->{
			dtm.addRow(new Object [] {
					getNo(),
					sales_num,
					roomId,
					g.getNumber(),
					g.getSpell(),
					g.getName(),
					n,
					g.getUnit(),
					g.getPurchase_price(),
					g.getPurchase_price()*n,
					ss.findByRoomId(roomId).getCome_date(),
					ss.findByRoomId(roomId).getLeave_date(),
					CastUtil.format(new Date(), CastUtil.TIME_DATE_PATTERN),
			});


		});


		//序号初始化
		i=1;
	}

	//序号
	private  int i=1;
	public  int getNo() {
		return i++;
	}
}

